import nacos
import asyncio

import yaml
import app.settings as settings


# 初始化 Nacos 客户端
client = nacos.NacosClient(settings.NACOS_SERVER_ADDRESS, namespace=settings.NACOS_NAMESPACE,
                           username=settings.NACOS_USERNAME, password=settings.NACOS_PASSWORD)


def register_service():
    
    client.add_naming_instance(
        settings.SERVICE_NAME, settings.SERVICE_IP, settings.SERVICE_PORT)
    print("Registering service...",client)


async def send_heartbeat():
    while True:
        try:
            client.send_heartbeat(settings.SERVICE_NAME,
                                  settings.SERVICE_IP, settings.SERVICE_PORT)
        except Exception as e:
            print(f"Failed to send heartbeat: {e}")
        await asyncio.sleep(10)  # 每10秒发送一次心跳


def load_config(content):
    yaml_config = yaml.full_load(content)
    print("yaml_config:", yaml_config)
    lang = yaml_config['lang']
    settings.set_lang(lang)


def nacos_config_callback(args):
    content = args['raw_content']
    load_config(content)


def watch_config():
    # 启动时，强制同步一次配置
    config = client.get_config(settings.NACOS_DATA_ID,
                               settings.NACOS_GROUP_NAME)
    print("config:", config)
    load_config(config)
    # 启动监听器
    client.add_config_watcher(settings.NACOS_DATA_ID,
                              settings.NACOS_GROUP_NAME, nacos_config_callback)
